const express = require("express");
const { Category, Course } = require("../models/index");
const { success, fail } = require("../utils/response");
const { BadRequest } = require("http-errors");

const router = express.Router();

// 获取课程，根据传入的分类
router.get("/", async (req, res) => {
  try {
    const { CategoryId, pageNum, pageSize } = req.query;
    if (!CategoryId) {
      throw new BadRequest("缺少分类id");
    }
    const conditions = getConditions(req);
    conditions.attributes = { exclude: ["content"] };
    const { rows, count } = await Course.findAndCountAll(conditions);
    success(res, "获取课程成功", {
      list: rows,
      total: count,
      pageNum,
      pageSize,
    });
  } catch (error) {
    fail(res, error);
  }
});

// 获取参数
function getConditions(req) {
  const { keywords, pageNum, pageSize, CategoryId, UserId, isRecommend } = req.query;
  const conditions = {
    where: {},
  };
  // 分页参数，没传分页 就是查询所有
  const page = Math.abs(pageNum);
  const size = Math.abs(pageSize);
  if (page && size) {
    conditions.offset = (page - 1) * size;
    conditions.limit = size;
  }
  // 处理普通参数
  if (keywords) {
    conditions.where.name = {
      [Op.like]: `%${keywords}%`,
    };
  }
  if (CategoryId) {
    conditions.where.CategoryId = CategoryId;
  }
  if (UserId) {
    conditions.where.UserId = UserId;
  }
  if (isRecommend) {
    conditions.where.isRecommend = isRecommend;
  }
  return conditions;
}

module.exports = router;
